from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from slowapi import Limiter
from slowapi.util import get_remote_address
from fastapi.middleware.cors import CORSMiddleware
from module.model import QueryContent
from plugins.plugin import traslate


app = FastAPI(docs_url="/swagger")

# 添加 CORS 支持
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

limiter = Limiter(key_func=get_remote_address)

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    response = await call_next(request)
    return response

@app.post("/api/translate")
@limiter.limit("5/10seconds")  # 每个IP每10秒最多10次请求
async def translate(request: Request, querycontent: QueryContent):
    result, status = traslate(querycontent.text, querycontent.target_lang)
    if status:
        return {'code': 200, 'msg': 'success', 'data': result}
    else:
        return {'code': 500, 'msg': 'failed', 'data': result}

@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    if exc.status_code == 429:
        # 自定义限速响应
        return JSONResponse(status_code=429, content={"detail": "Too Many Requests"})
    return await request.app.default_exception_handler(request, exc)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001)